<template>
  <div style="padding-left: 10px;">
    <div class="form-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="站点名称">
          <el-input v-model="formInline.stationName" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="formInline.stationKey" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="报警类型">
          <el-select v-model="formInline.type" placeholder="" clearable style="width: 200px;">
            <el-option label="爆管预警" value="1" />
            <el-option label="压力过高" value="3" />
            <el-option label="余氯低限" value="6" />
            <el-option label="浊度超限" value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="value1" type="daterange" range-separator="至" start-placeholder="" end-placeholder="" :disabled-date="disabledDate"
            :size="size" @change="changeTime"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exPort">导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="chongzhi">重置</el-button>
        </el-form-item>
      </el-form>

    </div>
    <div class="boxTable">
      <el-table :data="paginatedData" border v-loading="loading" element-loading-text="加载中..." style="height:95%;">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column v-for="(header, index) in headers" :key="index" :prop="header.prop" :label="header.label"
          :width="header.width" />
      </el-table>
    </div>
    <!-- <div v-if="tableData.length === 0"> -->
      <!-- <el-empty description="暂无数据" /> -->
    <!-- </div> -->
    <div class="pagination-container"> <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="totalItems"
        :page-size="pageSize" :current-page="currentPage" @current-change="handlePageChange"
        @size-change="handleSizeChange" /></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { reactive } from 'vue'
import { AlarmRecord } from '../../http/http'
const currentPage = ref(1);
const pageSize = ref(20);
const tableData = ref([]);
const startTime = ref(null);
const endTime = ref(null);
const today = new Date();
const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0); // 今天的开始时间 00:00:00
const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999); // 今天的结束时间 23:59:59.999

const value1 = ref([startDate, endDate]);

console.log(value1.value); // 输出: [今天的日期 00:00:00, 今天的日期 23:59:59.999]

const TimeValue = value1.value.map( timeString =>{
  const date = new Date(timeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
})

console.log(TimeValue,'TimeValue');
startTime.value = TimeValue[0]
endTime.value = TimeValue[1]

const loading = ref(false)
import * as XLSX from 'xlsx'
const formInline = reactive({
  type: '3',
  stationKey: '',
  stationName: '',
  date: new Date(),
})
// 判断禁用日期的逻辑
const disabledDate = (time) => {
  return time.getTime() > Date.now() // 禁用今天之后的所有日期
}

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

//清楚日期
// function clearInput(){
//   console.log('日期清空了');
  
// }
function handleSizeChange(){
  pageSize.value = size;
  currentPage.value = 1; // 当每页条目数变化时，将页码重置为 1
}
function changeTime(e) {
  // 转换为本地时间
  const localTimes = e.map(timeString => {
    const date = new Date(timeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
  });

  console.log(localTimes);
  startTime.value = localTimes[0]
  endTime.value = localTimes[1]

}
function dialogData() {
  return {
    "startTime": startTime.value,
    "endTime": endTime.value,
    "stationKey": formInline.stationKey,  //设备编号
    "warnType": formInline.type, //监测类型
    "stationname": formInline.stationName  //监测类型
  }
}

function chongzhi(){
  // value1.value = ''
  formInline.stationKey = '',
  formInline.type = '',
  formInline.stationName = ''
// 默认展示当天日期的开始和结束时间
const today = new Date();
const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0); // 今天的开始时间 00:00:00
const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999); // 今天的结束时间 23:59:59.999
  value1.value = [startDate, endDate],

console.log(value1.value); // 输出: [今天的日期 00:00:00, 今天的日期 23:59:59.999]
const TimeValue = value1.value.map( timeString =>{
  const date = new Date(timeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整为1-12
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 格式化为 YYYY-MM-DD
})

console.log(TimeValue,'TimeValue');

}
onMounted(() => {
  onSubmit()
})

const onSubmit = () => {
  loading.value = true
  console.log(dialogData(), 'parms');
  AlarmRecord(dialogData()).then((res) => {
    tableData.value = res.data.returnValue.result
    console.log(tableData.value, '历史报警');
    tableData.value.forEach(i =>{
      i.value = Number(Number(i.value).toFixed(4));  
      const valueNumber = i.information.slice(0, 2)
                switch (valueNumber) {// 添加单位字段
                    case '余氯':
                        i.value = ensureUnit(i.value, 'mg/L')
                        break;
                    case '浊度':
                        i.value = ensureUnit(i.value, 'NTU')
                        break;
                    case '压力':
                        i.value = ensureUnit(i.value, 'Mpa')
                    case '爆管':
                        i.value = ensureUnit(i.value, 'Mpa')
                        break;
                }
      })
    if (res.status === 200) {
      loading.value = false
    }
  })
}

function ensureUnit(value, unit) {
    if (typeof value === 'number') {
        return `${value}${unit}`;
    } else if (typeof value === 'string') {
        // 检查是否已经包含单位
        if (!value.endsWith(unit)) {
            return `${value}${unit}`;
        }
        return value;
    }
    return value;  // 如果不是数字或字符串，直接返回原值
}
// 导出功能
const exPort = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new()
  // 将表头数据和表格数据转换为工作表
  const wsData = tableData.value.map(row => {
    const newRow = {}
    headers.value.forEach(header => {
      newRow[header.label] = row[header.prop] // 用表头的 label 作为列名
    })
    return newRow
  })

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(wsData, { header: headers.value.map(header => header.label) })

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 生成文件并触发下载
  XLSX.writeFile(wb, '报警台账.xlsx')
}


// 定义表头数据
const headers = ref([
  { prop: 'starttime', label: '报警时间', },
  { prop: 'stationname', label: '站点名称', },
  // { prop: 'monitorname', label: '监测类型名称' },
  { prop: 'information', label: '报警类型', },
  { prop: 'stationkey', label: '设备编号' },
  { prop: 'value', label: '报警值', }
])

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = currentPage.value * pageSize.value;
  return tableData.value.slice(start, end);
});

// 总条目数
const totalItems = computed(() => tableData.value.length);

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};
</script>

<style scoped>
.form-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  /* height: 100vh; 使容器高度占满整个视口 */
}

.boxTable {
  height: 800px;
  position: relative;
  padding-left: 50px;
}

.pagination-container {
  position: fixed;
  right: 0;
  bottom: 0;
  z-index: 999;
}
</style>